import 'package:flutter/material.dart';
import 'package:kq_flutter_core_widget/utils/kq_screen_util.dart';
import 'package:kq_flutter_core_widget/widgets/button/kq_ink_well.dart';
import 'package:kq_flutter_core_widget/widgets/imageBox/kq_image_box.dart';
import 'package:kq_flutter_core_widget/utils/file_preview_util.dart';
import 'package:kq_flutter_core_widget/widgets/image/kq_image.dart';
import 'package:kq_flutter_core_widget/utils/ex/kq_ex.dart';
import 'package:kq_flutter_widgets/config/kq_global.dart';
import 'package:kq_flutter_widgets/resources/images.dart';
import 'package:kq_flutter_widgets/resources/kq_theme_colors.dart';
import 'package:kq_flutter_widgets/theme/kq_theme_manager.dart';
import 'package:kq_flutter_widgets/widgets/divider/kq_divider.dart';
import 'package:kq_flutter_widgets/widgets/image/kq_print_image.dart';
import 'package:kq_flutter_widgets/widgets/overflowBox/kq_over_flow_box.dart';
import 'package:kq_flutter_widgets/widgets/wrapFlow/kq_auto_column_flow.dart';

enum SelectDividePosition {
  /// 头部
  top,

  /// 底部
  bottom
}

// ignore: must_be_immutable
class KqSelectCard extends StatefulWidget {
  /// 卡片宽度
  final double? cardWidth;

  /// 图片url
  final String? url;

  /// 多张模具/产品图片,用于图片预览
  final String? allPic;

  /// 选中状态，默认未选中
  bool isSelect = false;

  /// 图片类型
  final ImageType imgType;

  /// 默认图片
  final String defaultPic;

  /// 标题
  final String? title;

  /// 副标题
  final String? subTitleImg;

  /// 副标题内容
  final String? subTitle;

  /// 第二个副标题
  final String? subSecondTitleImg;

  /// 第二个副标题内容
  final String? subSecondTitle;

  /// 分隔线位置,未设置就不显示
  final SelectDividePosition? dividePosition;

  /// 分隔线高度 默认：12.r
  final double? divideHeight;

  /// 底部widget,和bottomBtns实现一种
  final Widget? bottomBtnsView;

  /// 底部widget,和bottomBtnsView实现一种
  final List<Widget>? bottomBtns;

  /// tags 标签
  List<Widget>? tags;

  /// 印章类型，使用[KqPrintType]
  final KqPrintType? printType;

  /// 卡片信息内容个数
  final int totalCount;

  /// 行数
  final int Function()? rowCountCallback;

  ///每行的列数
  final int Function(int row)? renderCrossAxisCountCallback;

  ///icon
  final String Function(int row, int column)? renderIconPathCallback;

  ///Text
  final String Function(int row, int column)? renderTextCallback;

  /// 指定位置的右边widget自定义
  final Widget? Function(int row, int column)? renderWidgetCallback;

  ///Text行数
  final int Function(int row, int column) renderTextMaxLineCallback;
//00008120-000610A83C98201E
  /// 点击
  final void Function()? onTap;

  /// 进度条：当前进度值
  final double Function()? renderProgressValueCallback;

  /// 进度条：总的进度值
  final double Function()? renderTotalProgressValueCallback;

  /// 进度条：左边的widget
  final Widget Function()? renderProgressLeftWidgetCallback;

  /// 进度条：右边的widget
  final Widget Function()? renderProgressRightWidgetCallback;

  KqSelectCard(
      {this.cardWidth,
      this.url,
      this.allPic,
      required this.isSelect,
      required this.imgType,
      required this.defaultPic,
      this.title,
      this.subTitleImg,
      this.subTitle,
      this.subSecondTitleImg,
      this.subSecondTitle,
      this.dividePosition,
      this.divideHeight,
      this.bottomBtnsView,
      this.bottomBtns,
      this.tags,
      this.printType,
      this.onTap,
      this.renderIconPathCallback,
      this.renderTextCallback,
      this.renderWidgetCallback,
      this.renderProgressValueCallback,
      this.renderTotalProgressValueCallback,
      this.renderProgressLeftWidgetCallback,
      this.renderProgressRightWidgetCallback,
      required this.totalCount,
      required this.renderCrossAxisCountCallback,
      required this.rowCountCallback,
      required this.renderTextMaxLineCallback,
      super.key});

  @override
  State<KqSelectCard> createState() => _KqSelectCardState();
}

class _KqSelectCardState extends State<KqSelectCard> {
  double widgetWidth = KqScreenUtil().screenWidth;

  /// 水平间距
  double spacing = 8.r;

  /// 垂直方向间距
  double runSpacing = 6.r;

  @override
  Widget build(BuildContext context) {
    return Container(
      // color: KqThemeColors.bgDialog,
      color: KqThemeColors.bgWhite,
      width: widget.cardWidth ?? double.infinity,
      child: KqInkWell(
        onTap: () {
          widget.onTap?.call();
        },
        enableRipple: false,
        child: renderContent(),
      ),
    );
  }
//

  Widget renderContent() {
    return Column(
      mainAxisAlignment: MainAxisAlignment.start,
      crossAxisAlignment: CrossAxisAlignment.stretch,
      children: [
        renderTopDividerWidget(),
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            renderSelectStatusWidget(),
            Expanded(
                child: Column(
              crossAxisAlignment: CrossAxisAlignment.stretch,
              children: [
                renderTitleWidget(),
                SizedBox(
                  height: 16.r,
                ),
                renderProgressWidget(),
                renderWrapFlowWidget(),
                renderBottomViewDivider(),
                renderBottomViewWidget(),
              ],
            ))
          ],
        ),
        renderBottomDividerWidget(),
      ],
    );
  }

  Widget renderSelectStatusWidget() {
    return SizedBox(
      width: 44.r,
      height: 80.r,
      child: Padding(
        padding: EdgeInsets.only(left: 2.r),
        child: Align(
          child: Image.asset(
            widget.isSelect
                ? Images.commonIcYixuan16Fang
                : Images.commonIcWeixuan16Fang,
            width: 14.r,
            height: 14.r,
            package: KqGlobal.packageName,
          ),
        ),
      ),
    );
  }

  Widget renderTopDividerWidget() {
    return Visibility(
        visible: widget.dividePosition != null &&
            widget.dividePosition == SelectDividePosition.top,
        child: KqDivider(
          height: widget.divideHeight ?? 8.r,
          color: KqThemeColors.bgTransparent,
        ));
  }

  Widget renderTitleWidget() {
    return Container(
      margin: EdgeInsets.only(top: 12.r),
      padding: EdgeInsets.only(right: 12.r),
      child: Row(
        children: [
          InkWell(
            onTap: () {
              if (widget.allPic.isNotNullOrEmpty) {
                List urls = widget.allPic!.split(',');
                if (urls.isNotNullOrEmpty) {
                  if (urls.length == 1) {
                    /// 单张预览
                    FilePreviewUtil.previewSingleImg(ImageUrl(
                        imageType: widget.imgType, url: widget.url ?? ''));
                  } else {
                    /// 多张预览
                    List<ImageUrl> imgs = urls
                        .map((e) => ImageUrl(imageType: widget.imgType, url: e))
                        .toList();
                    FilePreviewUtil.previewImg(imgs);
                  }
                } else {
                  FilePreviewUtil.previewSingleImg(ImageUrl(
                      imageType: widget.imgType, url: widget.url ?? ''));
                }
              } else {
                FilePreviewUtil.previewSingleImg(
                    ImageUrl(imageType: widget.imgType, url: widget.url ?? ''));
              }
            },
            child: KqImage.custom(
                imageType: widget.imgType,
                radius: 4.r,
                url: widget.url ?? '',
                width: 44.r,
                height: 44.r,
                fit: BoxFit.cover,
                errorImage: widget.defaultPic),
          ),
          Expanded(child: renderTitleInfo()),
        ],
      ),
    );
  }

  Widget renderProgressWidget() {
    if (widget.renderProgressValueCallback != null &&
        widget.renderTotalProgressValueCallback != null) {
      double? currentProgress = widget.renderProgressValueCallback!();
      double? totalProgress = widget.renderTotalProgressValueCallback!();
      Widget? leftWidget = widget.renderProgressLeftWidgetCallback?.call();
      Widget? rightWidget = widget.renderProgressRightWidgetCallback?.call();
      return Container(
          padding: EdgeInsets.only(right: 12.r, bottom: 12.r),
          child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                if (leftWidget != null) leftWidget,
                if (leftWidget != null)
                  SizedBox(
                    width: 12.r,
                  ),
                Expanded(
                    child: LinearProgressIndicator(
                  value:
                      totalProgress == 0 ? 0 : currentProgress / totalProgress,
                  color: KqThemeColors.textGreen,
                  backgroundColor: KqThemeColors.bgF0,
                  minHeight: 10.r,
                  borderRadius: BorderRadius.all(Radius.circular(10.r)),
                )),
                if (rightWidget != null)
                  SizedBox(
                    width: 16.r,
                  ),
                if (rightWidget != null) rightWidget,
              ]));
    }
    return Container();
  }

  Widget renderWrapFlowWidget() {
    return Container(
      margin: EdgeInsets.only(bottom: 12.r),
      padding: EdgeInsets.only(right: 12.r),
      child: renderWrapFlowContent(),
    );
  }

  List<Widget> renderTags() {
    List<Widget> tags = [];
    if (widget.tags != null) {
      for (var i = 0; i < widget.tags!.length; i++) {
        tags.add(widget.tags![i]);
        if (i != widget.tags!.length - 1) {
          tags.add(SizedBox(
            width: 6.r,
          ));
        }
      }
    }
    return tags;
  }

  Widget renderTitleInfo() {
    String title = widget.title ?? '';
    return Container(
      margin: EdgeInsets.only(left: 12.r),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Expanded(
                  child: Text(title.ellipsis(),
                      style: TextStyle(
                          fontSize: 14.sp, color: KqThemeColors.text26),
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis)),
              Visibility(
                  visible: widget.tags != null,
                  child: Container(
                    margin: EdgeInsets.only(top: 2.r),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: renderTags(),
                    ),
                  )),
            ],
          ),
          SizedBox(
            height: 4.r,
          ),
          renderSubTitleInfo()
        ],
      ),
    );
  }

  Widget renderSubTitleInfo() {
    String? subTitle = widget.subTitle ?? '';
    String? subSecondTitle = widget.subSecondTitle ?? '';
    return Row(
      children: [
        Visibility(
            visible: widget.subTitleImg != null ? true : false,
            child: Image.asset(
              widget.subTitleImg ?? '',
              width: 12.r,
              height: 12.r,
            )),
        Visibility(
            visible: subTitle.isNotNullOrEmpty &&
                widget.subTitleImg.isNotNullOrEmpty,
            child: SizedBox(
              width: widget.subTitleImg != null ? 8.r : 12.r,
            )),
        Visibility(
            visible: subTitle != '' && widget.subSecondTitleImg != null,
            child: Container(
              constraints: BoxConstraints(maxWidth: 120.r),
              child: Text(
                subTitle.ellipsis(),
                style: TextStyle(
                    fontSize:
                        KqThemeManager.getFormConfig().contentFontSize ?? 12.sp,
                    color: KqThemeColors.text59),
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
              ),
            )),
        Visibility(
            visible: subTitle != '' && widget.subSecondTitleImg == null,
            child: Expanded(
                child: Text(
              subTitle.ellipsis(),
              style: TextStyle(
                  fontSize:
                      KqThemeManager.getFormConfig().contentFontSize ?? 12.sp,
                  color: KqThemeColors.text59),
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
            ))),
        Visibility(
            visible: widget.subSecondTitleImg != null ? true : false,
            child: Image.asset(
              widget.subSecondTitleImg ?? '',
              width: 12.r,
              height: 12.r,
            )),
        Visibility(
            visible: subSecondTitle.isNotNullOrEmpty &&
                widget.subSecondTitleImg.isNotNullOrEmpty,
            child: SizedBox(
              width: widget.subSecondTitleImg != null ? 8.r : 12.r,
            )),
        Visibility(
            visible: subSecondTitle != '',
            child: Expanded(
              // constraints: BoxConstraints(maxWidth: 120.r),
              child: Text(
                subSecondTitle.ellipsis(),
                style: TextStyle(
                    fontSize:
                        KqThemeManager.getFormConfig().contentFontSize ?? 12.sp,
                    color: KqThemeColors.text59),
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
              ),
            )),
      ],
    );
  }

  Widget renderWrapFlowContent() {
    if (widget.printType != null) {
      return KqOverFlowBox(
          referenceWidget: KqAutoColumnFlow(
              spacing: spacing,
              runSpacing: runSpacing,
              fontSize: 12.r,
              iconWidth: 12.r,
              totalCount: widget.totalCount,
              renderCrossAxisCountCallback: widget.renderCrossAxisCountCallback,
              renderIconPathCallback: widget.renderIconPathCallback,
              renderTextCallback: widget.renderTextCallback,
              rowCountCallback: widget.rowCountCallback,
              renderTextMaxLineCallback: widget.renderTextMaxLineCallback),
          overflowBoxWidget: KqPrintImage(printType: widget.printType!),
          visible: true,
          position: BoxToReferencePosition.bottom,
          alignment: Alignment.bottomRight,
          maxWidth: 44.r,
          maxHeight: 44.r);
    }
    return KqAutoColumnFlow(
        spacing: spacing,
        runSpacing: runSpacing,
        fontSize: 12.r,
        iconWidth: 12.r,
        totalCount: widget.totalCount,
        renderCrossAxisCountCallback: widget.renderCrossAxisCountCallback,
        renderIconPathCallback: widget.renderIconPathCallback,
        renderTextCallback: widget.renderTextCallback,
        rowCountCallback: widget.rowCountCallback,
        renderWidgetCallback: widget.renderWidgetCallback,
        renderTextMaxLineCallback: widget.renderTextMaxLineCallback);
  }

  Widget renderBottomViewDivider() {
    return Visibility(
        visible: widget.bottomBtns != null || widget.bottomBtnsView != null,
        child: Padding(
          padding: EdgeInsets.symmetric(horizontal: 16.r),
          child: const KqDivider(),
        ));
  }

  Widget renderBottomViewWidget() {
    return Visibility(
        visible: widget.bottomBtns != null || widget.bottomBtnsView != null,
        child: renderBottomBtns());
  }

  Widget renderBottomBtns() {
    if (widget.bottomBtnsView != null) {
      return widget.bottomBtnsView ?? Container();
    } else if (widget.bottomBtns != null) {
      List<Widget> btns = [];
      for (var i = 0; i < widget.bottomBtns!.length; i++) {
        btns.add(widget.bottomBtns![i]);
        if (widget.bottomBtns!.length - 1 != i) {
          btns.add(SizedBox(
            width: 8.r,
          ));
        }
      }
      return Container(
        // height: 48.r,
        padding: EdgeInsets.symmetric(horizontal: 16.r, vertical: 8.r),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.end,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: btns,
        ),
      );
    }
    return Container();
  }

  Widget renderBottomDividerWidget() {
    return Visibility(
        visible: widget.dividePosition != null &&
            widget.dividePosition == SelectDividePosition.bottom,
        child: KqDivider(
          height: widget.divideHeight ?? 8.r,
        ));
  }
}
